﻿using JoyAdmin.Core;
using Furion;
using Furion.DatabaseAccessor;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Linq;
using System.Linq.Expressions;

namespace JoyAdmin.EntityFramework.Core
{
    [AppDbContext("SqliteConnectionString")]
    public class DefaultDbContext : AppDbContext<DefaultDbContext> 

    {
        public DefaultDbContext(DbContextOptions<DefaultDbContext> options) : base(options)
        {
             EnabledEntityStateTracked= false;
        }

        protected override void SavingChangesEvent(DbContextEventData eventData, InterceptionResult<int> result)
        {
            // 获取当前事件对应上下文
            var dbContext = eventData.Context;

            // 获取所有新增和更新的实体
            var entities = dbContext.ChangeTracker.Entries().Where(u => u.State == EntityState.Added || u.State == EntityState.Modified || u.State == EntityState.Deleted);
            var userId = App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value;
            var userName = App.User.FindFirst(ClaimConst.CLAINM_ACCOUNT)?.Value;
            if (userId == null)
            {

            }

            foreach (var entity in entities)
            {
                if (entity.Entity.GetType().IsSubclassOf(typeof(BaseEntity)))
                {
                    var obj = entity.Entity as BaseEntity;
                    if (entity.State == EntityState.Added)
                    {

                        obj.CreatedTime = DateTime.Now;
                        if (!string.IsNullOrEmpty(userId))
                        {
                            obj.CreatedUserId = long.Parse(userId);
                            obj.CreatedUser = userName;
                        }
                    }
                    else if (entity.State == EntityState.Modified)
                    {

                        obj.ModifiedTime = DateTime.Now;
                        if (!string.IsNullOrEmpty(userId))
                        {
                            obj.ModifiedUserId = long.Parse(userId);
                            obj.ModifiedUser = userName;
                        }
                        entity.Property(nameof(BaseEntity.CreatedTime)).IsModified = false;
                        entity.Property(nameof(BaseEntity.CreatedUserId)).IsModified = false;
                        entity.Property(nameof(BaseEntity.CreatedUser)).IsModified = false;
                    }
                }

            }
        }
        
        
    }
}